package mp

import (
	"duoke/model"
	"duoke/service"
	"duoke/utils/response"
	"duoke/utils/valid"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

var Home = new(homeCtl)

type homeCtl struct{}

func (ctl *homeCtl) Info(c *gin.Context) {
	info, err := service.AccountSetting.Info(c, "home")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", info)
}
func (ctl *homeCtl) Index(c *gin.Context) {
	var req model.ReqId
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	var m model.HomeResult
	ch := make(chan model.HomeResult, 3)

	go func() {
		where := fmt.Sprintf("parent_id = %d", req.Id)
		menu, err := service.HomePage.Infos(c, where, "*")
		ch <- model.HomeResult{Menu: menu, Err: err}
	}()
	go func() {
		where := fmt.Sprintf("menu_id = %d", req.Id)
		video, err := service.HomeVideo.Info(c, where, "*")
		ch <- model.HomeResult{Video: video, Err: err}
	}()
	go func() {
		where := fmt.Sprintf("menu_id = %d", req.Id)
		notice, err := service.HomeNotice.Infos(c, where, "*")
		ch <- model.HomeResult{Notice: notice, Err: err}
	}()

	for i := 0; i < 3; i++ {
		res := <-ch
		if res.Err != nil {
			response.Error(c, res.Err.Error(), nil)
			return
		}
		if res.Menu != nil {
			m.Menu = res.Menu
		}
		if res.Video != nil {
			m.Video = res.Video
		}
		if res.Notice != nil {
			m.Notice = res.Notice
		}
	}
	close(ch)
	// 获取编辑器
	response.Success(c, "获取成功", &model.HomeResult{
		Menu:    m.Menu,
		Banner:  m.Banner,
		Video:   m.Video,
		Content: m.Content,
		Notice:  m.Notice,
	})
}
